package com.blockmeta.bbs.businesslibrary.service;

/**
 * Created by bytom on 2018/5/25.
 */

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import com.blankj.utilcode.util.LogUtils;

import com.blankj.utilcode.util.LogUtils;
import com.blockmeta.bbs.baselibrary.base.app.BaseApp;
import com.blockmeta.bbs.baselibrary.utils.SharedPreferenceUtil;
import com.blockmeta.bbs.businesslibrary.activity.DeepLinkActivity;
import com.blockmeta.bbs.businesslibrary.constant.Constant;
import com.blockmeta.bbs.businesslibrary.pojo.PushParamsPOJO;
import com.blockmeta.bbs.businesslibrary.widget.ForegroundCallbacks;
import com.google.gson.Gson;
import com.igexin.sdk.GTIntentService;
import com.igexin.sdk.PushManager;
import com.igexin.sdk.message.GTCmdMessage;
import com.igexin.sdk.message.GTNotificationMessage;
import com.igexin.sdk.message.GTTransmitMessage;

/**
 * 继承 GTIntentService 接收来 个推的消息, 所有消息在线程中回调, 如果注册 该服务, 则务必要在 AndroidManifest中声明, 否则 法接
 受消息<br>
 * onReceiveMessageData 处 透传消息<br>
 * onReceiveClientId 接收 cid <br>
 * onReceiveOnlineState cid 离线上线通知 <br> * onReceiveCommandResult 各种事件处 回执 <br> */
public class MyGTIntentService extends GTIntentService {
    public MyGTIntentService() {
    }
    @Override
    public void onReceiveServicePid(Context context, int pid) {
        LogUtils.d("getuipush", "onReceiveServicePid -> " + "pid = " + pid);
    }

    //当服务端配置成通知加透传当模式的时候，会点击推送才收到透传消息
//    （1）安卓客户端收到通知，点击通知跳转到应用内对应页面的实现
//    服务端调接口推送的情况下：推送notificationtemplate transmissiontype设置成2 填写透传内容；客户端获取透传消息（intentservice中的onReceiveMessageData）处写跳转代码。
//    个推开发平台上推送启动应用通知的情况下：高级设置里面填写透传内容，强制启动设置成否；客户端获取透传消息（intentservice中的onReceiveMessageData）处写跳转代码。
//            （2）客户端接收到透传消息后为何立即打开了应用
//    代码推送：查看一下服务端代码TransmissionType设置的参数，参数为1时是强制启动应用，2是等待客户端处理；将该参数设置修改为2，将不立即打开应用。
//    平台推送：查看一下高级设置里面，强制启动应用设置的是否为开启，设置为关闭后，将不立即打开应用。
//            （3）推送了一条透传信息为什么获取不到透传
//    第一：服务端用的是否是通知加透传的消息模板，这种方式不能直接获取到透传消息，需要点击通知才能获取透传。
//    第二：intentservice在manifest中是否有配置。
//    第三：在intentservice中的onreceivemessagedata中获取。
    //服务端模版
//    public static TransmissionTemplate transmissionTemplateDemo(String appId, String appKey){ TransmissionTemplate template = new TransmissionTemplate(); template.setAppId(appId);
//        template.setAppkey(appKey);
//        template.setTransmissionContent("透传内容"); template.setTransmissionType(1);
//        Notify notify = new Notify(); notify.setTitle("请输入通知栏标题"); notify.setContent("请输入通知栏内容"); notify.setPayload(""); notify.setType(Type._payload);
////notify.setIntent("intent:#Intent;component=yourpackage/.YourActivity;S.parm1=value1;
////S.parm2=value2;end"); //notify.setType(Type._intent);
//// notify.setUrl("https://dev.getui.com/"); //notify.setType(Type._url); template.set3rdNotifyInfo(notify);//设置第三方通知 return template;
//    }

    /**
     * 以前会走的代码，现在升级后，推送不管在线离线都是走的直接打开deeplinkactivity，由服务端配置，里面可以获取到param7，除了在线的时候onNotificationMessageArrived和
     * onNotificationMessageClicked会被调用到。就这样吧
     * @param context
     * @param msg
     */
    @Override
    public void onReceiveMessageData(Context context, GTTransmitMessage msg) {
        LogUtils.d("getuipush", "onReceiveMessageData -> " + "msg length= " + msg.getPayload().length);
        String appid = msg.getAppid();
        String taskid = msg.getTaskId();
        String messageid = msg.getMessageId();
        byte[] payload = msg.getPayload();
        String pkg = msg.getPkgName();
        String cid = msg.getClientId();

        // 第三方回执调用接口，actionid范围为90000-90999，可根据业务场景执行
        boolean result = PushManager.getInstance().sendFeedbackMessage(context, taskid, messageid, 90001);
        LogUtils.d("getuipush", "call sendFeedbackMessage = " + (result ? "success" : "failed"));

        LogUtils.d("getuipush", "onReceiveMessageData -> " + "appid = " + appid + "\ntaskid = " + taskid + "\nmessageid = " + messageid + "\npkg = " + pkg
                + "\ncid = " + cid);

        if (payload == null) {
            LogUtils.e("getuipush", "receiver payload = null");
        } else {
            String data = new String(payload);
            boolean isForeground = ForegroundCallbacks.get(BaseApp.getApp()).isForeground();
            if (isForeground) {
                //前台  传递的上下文获取不到
                PushParamsPOJO pushParamsPOJO = new Gson().fromJson(data, PushParamsPOJO.class);
                if (!TextUtils.isEmpty(pushParamsPOJO.deeplink))
                {
                    Intent intent = new Intent(context, DeepLinkActivity.class);
                    intent.setData(Uri.parse(pushParamsPOJO.deeplink));
                    context.startActivity(intent);
                }
            } else {
                Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
                launchIntent.putExtra(Constant.PUSH_JSON, data);
                context.startActivity(launchIntent);
            }
        }
    }
    @Override
    public void onReceiveClientId(Context context, String clientid) {
        if (clientid != null) {
            SharedPreferenceUtil.putString(BaseApp.getApp(), Constant.GETUI_TOKEN, clientid);
            LogUtils.d("getuipush", "onReceiveClientId -> " + "clientid = " + clientid);
        }
    }
    @Override
    public void onReceiveOnlineState(Context context, boolean online) {
        LogUtils.d("getuipush", "onReceiveOnlineState -> " + "online = " + online);
    }
    @Override
    public void onReceiveCommandResult(Context context, GTCmdMessage cmdMessage) {
        LogUtils.d("getuipush", "onReceiveCommandResult -> " + "cmdMessage action= " + cmdMessage.getAction());
    }
    @Override
    public void onNotificationMessageArrived(Context context, GTNotificationMessage msg) {
        LogUtils.d("getuipush", "onNotificationMessageArrived -> " + "msg content= " + msg.getContent());
    }
    @Override
    public void onNotificationMessageClicked(Context context, GTNotificationMessage msg) {
        LogUtils.d("getuipush", "onNotificationMessageClicked -> " + "msg content= " + msg.toString());
    }
}
